package com.five.monkey.feign.es.service.impl;

import com.five.monkey.feign.es.convert.PageConvert;
import com.five.monkey.feign.es.convert.UserConvert;
import com.five.monkey.feign.es.dao.model.User;
import com.five.monkey.feign.es.dao.repository.UserRepository;
import com.five.monkey.feign.es.service.UserElasticsearchService;
import com.five.monkey.vo.PageVo;
import com.five.monkey.vo.UserVo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 狻猊
 * @date 2021-11-23 10:40:40
 */
@Service
public class UserElasticsearchServiceImpl implements UserElasticsearchService {

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserVo findById(Long id) {
        User user = userRepository.findById(id).orElse(null);
        return UserConvert.esModel2vo(user);
    }

    @Override
    public UserVo save(UserVo userVo) {
        User user = UserConvert.vo2esModel(userVo);
        if (Objects.nonNull(user)) {
            user = userRepository.save(user);
            userVo = UserConvert.esModel2vo(user);
        }
        return userVo;
    }

    @Override
    public boolean deleteById(Long id) {
        userRepository.deleteById(id);
        return true;
    }

    @Override
    public List<UserVo> findAll() {
        List<UserVo> voList = Lists.newArrayList();
        userRepository.findAll().forEach(user -> voList.add(UserConvert.esModel2vo(user)));
        return voList;
    }

    @Override
    public PageVo<UserVo> findByStatus(Integer status, int page, int size, Sort sort) {
        PageRequest pageRequest;
        if (Objects.isNull(sort)) {
            sort = Sort.by(Sort.Order.asc("id"));
        }
        pageRequest = PageRequest.of(page, size, sort);
        Page<User> userPage = userRepository.findByStatus(status, pageRequest);
        return new PageConvert<User, UserVo>().page2vo(userPage, UserConvert::esModel2vo);
    }

    @Override
    public List<UserVo> findByStatus(Integer status, Sort sort) {
        if (Objects.isNull(sort)) {
            sort = Sort.by(Sort.Order.asc("id"));
        }
        List<User> userList = userRepository.findByStatus(status, sort);
        return userList.stream().map(UserConvert::esModel2vo).collect(Collectors.toList());
    }

}
